﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.TeamFoundation.TestManagement.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TestStepsEditor.Actions;

namespace TestStepsEditor
{
    public partial class LinkedTestCasesForm : Form
    {
        private readonly ITestManagementTeamProject _testproject;
        private ISharedStep sharedStep;
        private BindingList<TestCaseViewer> testCaseViewer;

        public LinkedTestCasesForm()
        {
            InitializeComponent();
        }

        public LinkedTestCasesForm(ITestManagementTeamProject testProject, string sharedStepID)
        {
            InitializeComponent();
            _testproject = testProject;
            LoadData(sharedStepID);
        }

        public void LoadData(string sharedStepID)
        {
            try
            {
                sharedStep = _testproject.SharedSteps.Find(Convert.ToInt32(sharedStepID));
            }
            catch (DeniedOrNotExistException ex)
            {
                MessageBox.Show(@"Could not load work item: " + ex.Message, @"Work Item Load Error");
                return;
            }
            if (sharedStep != null)
            {
                testCaseViewer = new BindingList<TestCaseViewer>();
                _linkedTestCasedataGridView.SuspendLayout();
                Enabled = false;
                foreach (ITestCase testCase in sharedStep.TestCaseReferences)
                {
                    testCaseViewer.Add(new TestCaseViewer(testCase.Id, testCase.Title));
                }
                _linkedTestCasedataGridView.DataSource = testCaseViewer;
                Enabled = true;
                _linkedTestCasedataGridView.ResumeLayout(true);
                _linkedTestCasedataGridView.AutoResizeRows();
                _linkedTestCasedataGridView.AutoResizeColumns();
                _linkedTestCasedataGridView.AllowUserToAddRows = false;
                _linkedTestCasedataGridView.ReadOnly = true;
            }
        }

        private void _linkedTestCasedataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            var form =
                new MainForm(
                    Convert.ToInt32(
                        _linkedTestCasedataGridView.Rows[_linkedTestCasedataGridView.CurrentRow.Index].Cells[0].Value.
                            ToString()));
            //form._testStepsGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;            
            form.Show();
            Rows.MakeSharedStepsReadOnly(form.workItemGridView);
            form.Refresh();
        }
    }
}